<template>
  <div name="addForm">
    <el-card>
      <div slot="header" class="clearfix">
        <div>督导员听课评价表(未提交)</div>
      </div>

      <el-form
        :model="form"
        ref="addForm"
        label-width="140px"
        class="demo-ruleForm"
      >
        <el-form-item label="课程类型">
          <el-input
            :disabled="true"
            v-model="classType"
            style="width: 140px"
          ></el-input>
        </el-form-item>
        <el-form-item label="督导员">
          <el-input
            :disabled="true"
            v-model="form.supervisor"
            style="width: 140px"
          ></el-input>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item label="听课学期">
          <el-select v-model="form.semester" placeholder="请选择听课学期">
            <el-option
              :label="item"
              v-for="item in semesterList"
              :key="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="听课时间">
          <el-form-item>
            <el-date-picker
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择听课时间"
              v-model="form.listenDate"
              style="width: 300px"
            ></el-date-picker>
          </el-form-item>
        </el-form-item>
        <el-form-item label="听课节数">
          <el-checkbox-group v-model="form.listenTimeArray">
            <el-checkbox
              v-for="(item, index) in timeList"
              :key="item + index"
              :label="'' + item"
              >{{ "第" + item + "节" }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="听课地点">
          <el-input
            v-model="form.listenAdd"
            placeholder="请输入听课地点"
            style="width: 350px"
          ></el-input>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item label="授课教师姓名">
          <el-input
            v-model="form.tName"
            placeholder="请输入授课教师姓名"
            style="width: 180px"
          ></el-input>
        </el-form-item>
        <el-form-item label="所在学院">
          <el-select
            v-model="form.tNameInSchool"
            placeholder="请选择授课教师所在学院"
          >
            <el-option
              :label="item"
              v-for="item in schoolInfo"
              :key="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程名称">
          <el-input
            v-model="form.courseName"
            placeholder="请输入课程名"
            style="width: 140px"
          ></el-input>
        </el-form-item>
        <el-form-item label="课程类别">
          <el-select v-model="form.courseType" placeholder="请选择课程类别">
            <el-option label="必修课" value="必修课"></el-option>
            <el-option label="选修课" value="选修课"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="授课班级">
          <el-input
            v-model="form.className"
            placeholder="请输入授课班级"
            style="width: 140px"
          ></el-input>
        </el-form-item>
        <el-form-item label="学生所在学院">
          <el-select
            v-model="form.stuInSchool"
            placeholder="请选择学生所在学院"
          >
            <el-option
              :label="item"
              v-for="item in schoolInfo"
              :key="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="应到人数">
          <el-input
            v-model.number="form.allNum"
            style="width: 140px"
            placeholder="请输入应到人数"
            @change="onAllNum"
          ></el-input>
        </el-form-item>
        <el-form-item label="实到人数">
          <el-input
            v-model.number="form.factNum"
            style="width: 140px"
            placeholder="请输入实到人数"
            @change="onFactNum"
          ></el-input>
        </el-form-item>
        <el-divider></el-divider>
        <!-- 评价单选处 -->
        <div
          class="mt-2"
          v-for="(groupItem, groupKey, groupIndex) in staticInfo"
          :key="groupKey"
        >
          <!-- 判断时为了不报错 -->
          <div
            v-if="groupItem[0]"
            :title="groupItem[0].groupName"
            title-class="cell-title-class"
          />

          <el-collapse v-model="groupActiveNames[groupIndex]">
            <el-collapse-item
              :title-class="
                item.selected ? 'item-class-selected' : 'item-class'
              "
              v-for="item in groupItem"
              :label="item.selected"
              label-class="selected-lable-class"
              :key="item.id"
              :title="
                +groupItem[0].groupSort === 1
                  ? item.targetSort + '、' + item.targetName
                  : item.targetName
              "
              :name="item.targetSort"
            >
              <!-- 这里直接传入对象是为了修改值 -->
              <el-radio-group :value="item.selected">
                <el-radio
                  :label="selectItem"
                  v-for="(selectItem, selectIndex) in item.contentArray"
                  :name="item.targetName"
                  :key="selectIndex"
                  @change="handleSelected(selectItem, item)"
                  >{{ selectItem }}</el-radio
                >
              </el-radio-group>
            </el-collapse-item>
          </el-collapse>
        </div>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>总体评价</span>
          </div>
          <el-radio-group :value="form.evaluation">
            <el-radio
              :name="item"
              :label="item"
              v-for="(item, index) in selectedOptions"
              :key="index"
              @change="handleEvaluationSelected(item)"
              >{{ item }}</el-radio
            >
          </el-radio-group>
        </el-card>

        <el-form-item label="评价意见和建议">
          <el-input
            type="textarea"
            v-model="form.evaluationDetail"
            placeholder="请输入评价信息"
            :autosize="{ minRows: 8, maxRows: 20 }"
          ></el-input>
        </el-form-item>

        <!-- 表单根部 -->
        <el-form-item>
          <el-button type="warning" @click="onSubmit(false)"
            >暂存(保留已填写内容)</el-button
          >
          <el-button
            type="primary"
            style="margin-left: 100px"
            @click="onSubmit(true)"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
      <!-- 解释 -->

      <div class="tip-container" v-html="notions"></div>
    </el-card>
  </div>
</template>

<script>
import { getStaticInfo, editInfo, getDetails } from "../../api/data";

import { getSchoolInfo, getSemesterInfo } from "../../api/dictionaries";

export default {
  name: "addForm",
  props: {
    id: {
      type: String,
      default: "",
    },
  },
  created() {
    this.fetchSemesterInfo();
    this.fetchSchoolInfo();
    if (this.id) {
      this.fetchDetails();
      return;
    }
    if (this.$route.query.selectedType) {
      this.selectedType = this.$route.query.selectedType;
      this.fetchStaticInfo();
      return;
    }
  },
  data() {
    return {
      // 学期数据表
      semesterList: null,
      semester: null,
      // 类型id
      selectedType: "",
      //类型名称
      classType: "",
      //学院信息
      schoolInfo: [],
      //听课节数列表
      timeList: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
      currentTime: new Date(),
      form: {
        // 学期
        semester: "",
        id: "",
        tName: "",
        tNameInSchool: "",
        courseName: "",
        courseType: "",
        className: "",
        stuInSchool: "",
        allNum: "",
        factNum: "",
        attendance: "",
        evaluation: "",
        evaluationDetail: "",
        supervisor: this.$store.getters.name,
        listenDate: "",
        listenTimeArray: [],
        listenAdd: "",
        targets: [],
        status: 0,
      },
      activeNames: ["1"],
      selectedOptions: ["优", "良", "中", "合格", "不合格"],
      groupActiveNames: [[], [], [], [], []],
      staticInfo: {
        group1: [],
        group2: [],
        group3: [],
        group4: [],
        group5: [],
      },
      notions: "",
    };
  },
  methods: {
    onAllNum(val) {
      if (val < 0) {
        this.$message.error("应到人数输入无效!");
        this.form.factNum = null;
        return;
      }
    },
    onFactNum(val) {
      if (val < 0) {
        this.$message.error({
          message: "实到人数输入无效!",
          duration: 1000,
        });
        this.form.factNum = null;
        return;
      } else if (!this.form.allNum) {
        this.$message.error({
          message: "请先输入应到人数",
          duration: 1000,
        });
        this.form.factNum = null;
        return;
      } else if (this.form.factNum > this.form.allNum) {
        this.$message.error({
          message: "实到人数不应该超过应到人数",
          duration: 1000,
        });
        this.form.factNum = null;
        return;
      }
    },

    handleEvaluationSelected(val) {
      if (val === this.form.evaluation) {
        this.form.evaluation = "";
      } else {
        this.form.evaluation = val;
      }
    },
    //单选选择相同的选择
    handleSelected(name, item) {
      if (name == item.selected) {
        this.$forceUpdate();
        this.$set(item, "selected", "");
      } else {
        this.$forceUpdate();
        this.$set(item, "selected", name);
      }
    },

    async onSubmit(isSubmit) {
      //验证
      this.form.listenDay = this.form.listenDate;
      if (isSubmit) {
        if (Number(this.form.allNum) < Number(this.form.factNum)) {
          return this.$message.error({
            duration: 1000,
            message: "实到人数应小于应到人数",
          });
        }
        for (let item in this.form) {
          if (typeof this.form[item] === "string" && item !== "attendance") {
            this.form[item] = this.form[item].trim();
            if (!this.form[item]) {
              return this.$message.error({
                duration: 1000,
                message: "填写完所有选项才能提交！",
              });
            }
          } else if (item === "listenTimeArray") {
            if (this.form[item].length === 0) {
              return this.$message.error({
                duration: 1000,
                message: "填写完所有选项才能提交！",
              });
            }
          } else if (item === "targets") {
            //用做判断
            let result = true;
            for (let group in this.staticInfo) {
              result = this.staticInfo[group].every((value) => {
                return value.selected ? true : false;
              });
              if (!result) {
                break;
              }
            }
            if (!result) {
              return this.$message.error({
                duration: 1000,
                message: "填写完所有选项才能提交！",
              });
            }
          }
        }
      }
      if (Number(this.form.allNum) === 0) {
        this.form.attendance = "0.00%";
      } else {
        this.form.attendance =
          Math.round(
            (Number(this.form.factNum) / Number(this.form.allNum)) * 10000
          ) /
            100 +
          "%";
      }
      this.form.targets = [];
      for (let group in this.staticInfo) {
        this.staticInfo[group].forEach((value) => {
          const target = {};
          target.id = value.id;
          target.content = value.selected;
          this.form.targets.push(target);
        });
      }

      this.form.status = isSubmit ? 1 : 0;
      // 如果没有学期就给个默认学期
      if (!this.form.semester.trim()) {
        this.form.semester = this.semester;
      }
      console.log("暂存提交的表单数据对象");
      console.log(this.form);
      const res = await editInfo(this.form);
      console.log("提交响应结果");
      console.log(res);
      if (res.status === 200) {
        this.$message({
          type: "success",
          message: isSubmit ? "提交成功！" : "保存成功",
          duration: 1000,
        });

        this.$router.push("/home");
      }
    },

    async fetchSchoolInfo() {
      const res = await getSchoolInfo();
      if (res.status === 200) {
        res.data.result.forEach((value) => {
          this.schoolInfo.push(value.name);
        });
      }
    },
    async fetchSemesterInfo() {
      let { data: res } = await getSemesterInfo();
      let list = [];
      let semesterArr = res.result;
      semesterArr.forEach((item) => {
        list.push(item.name);
      });
      this.semesterList = list;
      this.semester = list[0];
    },
    async fetchStaticInfo() {
      const res = await getStaticInfo(this.selectedType);
      if (res.status === 200) {
        // 详情页

        this.$router.replace(`/listen/details/${res.data.result.id}`);
      }
    },
    async fetchDetails() {
      const res = await getDetails(this.id);
      if (res.status === 200) {
        // 课表数据
        this.form = Object.assign({}, this.form, res.data.result);
        if (!this.form.semester.trim()) {
          this.form.semester = this.semester;
        }
        this.notions = res.data.result.notions;
        this.classType = res.data.result.type;
        this.form.listenDate = this.form.listenDay;
        this.form.listenTimeArray = this.form.listenTimeArray.map((value) => {
          return Number(value);
        });
        if (this.form.listenDate) {
          this.currentTime = new Date(this.form.listenDate);
        }
        let activeArr = [1, 1, 1, 1, 1];

        res.data.result.targets.forEach((value) => {
          // 增加一个属性
          value.selected = value.content;
          if (!value.selected) {
            value.selected = "";
          }
          // 将所有手风琴展开
          this.groupActiveNames[value.groupSort - 1].push(
            activeArr[value.groupSort - 1]
          );
          activeArr[value.groupSort - 1]++;

          switch (value.groupSort) {
            case 1:
              this.staticInfo.group1.push(value);
              break;
            case 2:
              this.staticInfo.group2.push(value);
              break;
            case 3:
              this.staticInfo.group3.push(value);
              break;
            case 4:
              this.staticInfo.group4.push(value);
              break;
            case 5:
              this.staticInfo.group5.push(value);
              break;
            // no default
          }
        });
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style scoped>
.el-card {
  width: 100%;
  height: 100%;
  margin-bottom: 1em;
}
.tip-container {
  color: #67c23a;
  font-size: 0.7em;
}

.item-class-selected {
  color: green;
  font-size: 14px !important;
}
.item-class {
  font-size: 14px !important;
}
</style>
